package team.bluepen.supermarket.service;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.Deserializer;
import org.apache.kafka.common.serialization.StringDeserializer;
import team.bluepen.supermarket.conf.KafkaProperties;
import team.bluepen.supermarket.data.entity.Product;

import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

/**
 * @author RollW
 */
public class ProductReceiver {
    private static final Deserializer<String> STRING_DESERIALIZER = new StringDeserializer();
    private final String topic;
    private final Consumer<Product> productConsumer;
    private final KafkaConsumer<String, String> kafkaConsumer;

    public ProductReceiver(KafkaProperties kafkaProperties, String topic,
                           Consumer<Product> productConsumer) {
        this.productConsumer = productConsumer;
        Properties properties = new Properties();
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaProperties.getBootstrapServers());
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, "ConsumerG1");
        properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        this.kafkaConsumer = new KafkaConsumer<>(
                properties,
                STRING_DESERIALIZER,
                STRING_DESERIALIZER);
        this.topic = topic;
        kafkaConsumer.subscribe(Collections.singletonList(topic));
    }

    private final ScheduledExecutorService scheduledExecutorService =
            Executors.newSingleThreadScheduledExecutor();

    public void start() {
        scheduledExecutorService.scheduleAtFixedRate(
                this::consumeProductMessage,
                0,
                500,
                TimeUnit.MILLISECONDS);
    }

    public void stop() {
        scheduledExecutorService.shutdown();
        kafkaConsumer.close();
    }

    public String getTopic() {
        return topic;
    }

    private void consumeProductMessage() {
        ConsumerRecords<String, String> records =
                kafkaConsumer.poll(Duration.of(30, ChronoUnit.SECONDS));
        for (ConsumerRecord<String, String> record : records) {
            final String deValue = record.value();
            Product product = Product.deserialize(deValue);
            productConsumer.accept(product);
        }
    }
}
